<script setup lang="ts">
import { reactive, useTemplateRef } from "vue";
import type { FormRules, ElForm } from "element-plus";
import { ElMessage } from "element-plus";
import { userLogin } from "@/services/modules/login";
import useLoginStore from "@/stores/modules/login/login";
import login from "@/stores/modules/login/login";
import router from "@/router";
import { localCache } from "@/utils/cache";
import { LOGIN_USER_NAME, LOGIN_USER_PASSWORD } from "@/constants";

const formRef = useTemplateRef<InstanceType<typeof ElForm>>("formRef");

const accountModel = reactive({
  account: localCache.getCache(LOGIN_USER_NAME) ?? "",
  password: localCache.getCache(LOGIN_USER_PASSWORD) ?? ""
});

const accountRule: FormRules = {
  account: [
    { required: true, message: "请输入账号", trigger: "blur" },
    {
      pattern: /^[0-9a-zA-Z]{6,20}$/,
      message: "长度需为 6 到 20 的数字或者字母",
      trigger: "change"
    }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { pattern: /^[0-9a-zA-Z]{3,}$/, message: "长度需为 3 位以上数字或者字母", trigger: "blur" }
  ]
};

const loginStore = useLoginStore();

const handleLogin = async (isRemPwd: boolean) => {
  await formRef.value?.validate(async (valid) => {
    if (valid) {
      const name = accountModel.account;
      const password = accountModel.password;
      if (isRemPwd) {
        localCache.setCache(LOGIN_USER_NAME, name);
        localCache.setCache(LOGIN_USER_PASSWORD, password);
      } else {
        localCache.removeCache(LOGIN_USER_NAME);
        localCache.removeCache(LOGIN_USER_PASSWORD);
      }
      await loginStore.userLoginAction({ name, password });
      ElMessage.success("登录成功");
    } else {
      ElMessage.error("账号密码验证失败");
    }
  });
};

defineExpose({
  handleLogin
});
</script>

<template>
  <el-form ref="formRef" :model="accountModel" :rules="accountRule" status-icon>
    <el-form-item prop="account" label="账号">
      <el-input placeholder="请输入账号" v-model="accountModel.account" />
    </el-form-item>
    <el-form-item prop="password" label="密码">
      <el-input
        placeholder="请输入密码"
        type="password"
        show-password
        v-model="accountModel.password"
      />
    </el-form-item>
  </el-form>
</template>

<style scoped></style>
